package com.hua.thread;
//死锁；多个线程抱着对方需要的资源，形成僵持状态
public class DeathLock {


//
public static void main(String[] args) {
    Makeup  g1= new Makeup(0, "灰姑娘");
    Makeup  g2 = new Makeup(0, "白雪公主");

    g1.start();
    g2.start();
}





}
class Lipstick {




}
class Mirror{

}
class Makeup extends Thread{
    //需要的资源只有一份，用static来保证
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlname;//使用的人

    Makeup(int choice,String girlname){
        this.choice = choice;
        this.girlname = girlname;
    }

    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //互相持有对方的锁，需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice==0){
            synchronized (lipstick){//获得口红的锁
                System.out.println(this.girlname+"获取口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror){//一秒钟后想获得镜子的锁
                System.out.println(this.girlname+"获得镜子的锁！");
            }
        }else {
            synchronized (mirror){//获得口红的锁
                System.out.println(this.girlname+"获得镜子的锁");
                Thread.sleep(2000);
        }
            synchronized (lipstick){//一秒钟后想获得镜子的锁
                System.out.println(this.girlname+"！获取口红的锁");
            }
    }
}}

